package handle

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/jhoncy/schelper/lib"
	"github.com/jhoncy/schelper/model"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"time"
)

type register struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
	Rule     string
	RealName string
	Avatar   string
}

type loginForm struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}


func SuperUserRegister(c *gin.Context) {
	req := register{}
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	var unique model.CoreAccount
	model.DB().Where("username = ?", req.Username).Select("username").First(&unique)
	if unique.Username != "" {
		c.JSON(http.StatusConflict, gin.H{"error": "username already exists"})
		return
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	model.DB().Create(&model.CoreAccount{
		Username: req.Username,
		RealName: req.RealName,
		Password: string(hash),
		Rule:     req.Rule,
		Avatar:   req.Avatar,
		CreateAt: time.Now(),
	})
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}


func SuperUserLogin(c *gin.Context) {
	req := loginForm{}
	if err := c.ShouldBindBodyWith(&req, binding.JSON); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "bad request"})
		return
	}
	var account model.CoreAccount
	if model.DB().Where("username = ?", req.Username).First(&account).RecordNotFound() {
		c.JSON(http.StatusBadRequest, gin.H{"error": "wrong username or password"})
		return
	}
	if err := bcrypt.CompareHashAndPassword([]byte(account.Password), []byte(req.Password)); err !=nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "wrong username or password"})
		return
	}
	token, err := lib.JwtAuth(account.Username, account.Rule)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status":"success",
		"token": token,
		"policy": account.Rule,
		"realName": account.RealName,
	})
}